#include "app_common.h"
#include <stdlib.h>
#include <sys/time.h>
#include <string.h>
#include <stdio.h>

long long app_common_getCurrentTime()
{
    struct timeval tv;
    // 获取当前时间
    gettimeofday(&tv, NULL);

    return tv.tv_sec * 1000 + tv.tv_usec / 1000; // tv_sec是秒，tv_usec是微秒，转换成毫秒
}

// 字节数组转16进制字符串
char *app_common_bytes2hexstr(char * bytes,int len)
{
    char *hexstr = (char *)malloc(len * 2 + 1);
    for (int i = 0; i < len; i++)
    {
        sprintf(hexstr + i * 2, "%02x", bytes[i]);
    }
    hexstr[len * 2] = '\0';
    // // 释放内存
    // free(hexstr);
    return hexstr;
}

// 16进制字符串转字节数组
int app_common_hexstr2bytes(char * hexstr,char * bytes_buff)
{
    for (size_t i = 0; i < strlen(hexstr); i+=2)
    {
        char temp[3] = {hexstr[i],hexstr[i+1],'\0'};
        sscanf(temp, "%2hhx", &bytes_buff[i/2]);
    }
    return strlen(hexstr)/2;
}

int app_common_printf_hex(char *hexstr, int len)
{
    for (size_t i = 0; i < len; i++)
    {
        printf("%02x",hexstr[i]);
    }
    printf("\n");
    return 0;
}
